var fondfell_url = '//' + window.location.host;  // 基础路径
//var fondfell_url = 'http://42.193.150.165';  // 基础路径
var phpurl = fondfell_url+ '/';   // 接口请求路径

var socket_url = '49.233.107.190';  // socket 路径
//var socket_url = '49.233.107.190';  // socket ip 路径

var root_url = phpurl+'chat/';
var base_url = root_url + 'html/';  // 文件基础路径

var imgurl = 'http://nl-storage.oss-cn-beijing.aliyuncs.com/';  // 图片路径

var appurl = phpurl + 'a.php';   // app下载地址
var share_url = phpurl;   // 分享路径

var myuserid = getCookie('userid') || 1;

var mysex = getCookie('sex');


function returnImg(url){
    if(!url)return url;
    if(url && (url.indexOf('disk/') != -1 || url.indexOf('public/') != -1) && url.indexOf('http') == -1) {
        return imgurl + url;
    } else {
        // 非在线地址 / 不缺少http前缀
        return url;
    }
}
function _ajax(urls, callback, data) {
    var url = urls.toLowerCase(); // 转为小写进行判断
    if (url.indexOf('.php') != -1) { // 原生
        var f_url = phpurl + 'apis/';
    } else if (url.indexOf('home/') != -1) { // tp3 
        //var f_url = phpurl + 'apis/index.php/';
        var f_url = phpurl + 'apis/';
    } else if (url.indexOf('api/') != -1) { // tp5
        //var f_url = phpurl + 'index.php/';
        var f_url = phpurl;
    } else if (url.indexOf('chats/index/out') != -1) { // tp5
        //var f_url = phpurl + 'index.php/';
        var f_url = phpurl;
    } else { // 后端封装
        var f_url = phpurl + 'apis/index.php?'
    }
    var headers = {};
    if (window.sessionStorage.getItem('kefu_token')) {
        headers = {
            'Authorization': window.sessionStorage.getItem('kefu_token')
        }
    }
    if (!data) {
        data = {};
    }
    var type = data.urlType ? data.urlType : 'post';
    async = data.async == 1 ? false : true;
    _log(f_url + urls)
    _log(JSON.stringify(data))
    $.ajax({
        headers: headers,
        url: f_url + urls,
        type: type,
        data: data,
        dataType: 'json',
        success: function (result) {
            // 成功
            callback(result)
        },
        error: function (err) {
            _log(JSON.stringify(err))
            if (err.status == 200) {
                callback(err)
            } else {
                _log('服务器错误');
            }
        }
    });
}


// 获取参数
function getParam() {
    var url = window.location.href;
    var result = {};
    url = url.split('?')[1];
    if (!url) {
        return result;
    } else {
        url = unescape(url);
        var arr = url.split('&');
        for (var i = 0, len = arr.length; i < len; i++) {
            var a = arr[i].split('=');
            result[a[0]] = decodeURIComponent(a[1]);
        }
        return result;
    }
}


var pagenum = 1; // 当前页码
var heigutgao = 0; // 滚动执行 1执行  0不执行
var pagesize = 10; // 每页数量
var pagecount = 10;
// 列表
function _lists(url, page, loading, data) {
    if (!data) {
        data = {};
    }
    data.pagecount = 10;
    data.pagesize = 10;
    data.page = page;
    pagenum = page;
    // if ($('#no_more').length == 0) {
    // 	$('body').append('<div id="no_more"></div>');
    // }
    _ajax(url, function (ret) {
        _log(JSON.stringify(ret))
        if (ret) {
            if (loading == 1) { // 上拉刷新时  初始化参数
                $('body').scrollTop(0);
                $('#no_more').text('加载更多');
                $('#no_more').removeClass('null');
                // 重置滚动统计
                heigutgao = 1;
                // pagenum = 0;
                // 停止刷新
                view.ffList = [];
            }
            heigutgao = 1;
            ret.result = ret.result ? ret.result : ret.data ? ret.data : [];
            if (page == 0) {
                view.ffList = [];
            }
            view.ffList = view.ffList.concat(ret.result);

            $('#no_more').text('加载更多');
            if (ret.result.length < pagecount) {
                heigutgao = 0;
                $('#no_more').text('没有更多了');
            }
            _log(view.ffList.length)
            if (view.ffList.length == 0) {
                $('#no_more').text('');
                $('#no_more').addClass('null');
            }
        } else {
            view.ffList = [];
            api.refreshHeaderLoadDone();
        }
    }, data)
}

// 滚动到底部
function _scrollToBottom(callback, dom) {
    $(document).ready(function () { //触底加载
        if (!dom) {
            window.addEventListener("scroll", function (e) {
                if ($(document).scrollTop() < 10) {
                    // 滚动到顶部
                }
                if (($(document).scrollTop()) >= ($(document).height() - $(window).height() - 10)) {
                    setTimeout(callback, 1000); // 增加延迟，避免加载过快而致加载失误
                }
            });
        } else {
            $(dom).on('scroll', function (e) {
                var st = $(dom).scrollTop();
                var h = $(dom).height();
                var sh = $(dom)[0].scrollHeight;
                if (st >= (sh - h - 10)) {
                    setTimeout(callback, 1000);
                }
            })
        }
    });
}

// 滚动到顶部
function _scrollToTop(callback, dom) {
    $(document).ready(function () { //触底加载
        if (!dom) {
            window.addEventListener("scroll", function (e) {
                // _log(window.pageYOffset)
                // _log($(document).scrollTop())
                if ($(document).scrollTop() == 0) {
                    // 滚动到顶部
                    setTimeout(callback, 1000);
                }
                // if (($(document).scrollTop()) >= ($(document).height() - $(window).height() - 10)) {
                //     setTimeout(callback, 100); // 增加延迟，避免加载过快而致加载失误
                // }
            });
        } else {
            $(dom).on('scroll', function (e) {
                var st = $(dom).scrollTop();
                var h = $(dom).height();
                var sh = $(dom)[0].scrollHeight;
                if (st == 0) {
                    setTimeout(callback, 1000);
                }

                // if (st >= (sh - h - 10)) {
                //     setTimeout(callback, 100);
                // }
            })
        }
    });
}


//judgeClear();
// 判断是否要清除sessionStorage
function judgeClear() {
    var l = getCookie('date');
    var n = new Date().getTime();
    if (!l) {
        setCookie('date', n);
        return;
    }
    var result = n - l > 12 * 60 * 60 * 1000 ? 1 : 0; // 12小时后清空
    if (result == 1) {
        clearCookie('user');
        clearCookie('date');
    }
}


// 设置sessionStorage
function setCookie(c_name, value) {
    if (!window.sessionStorage) {
        _msg("浏览器不支持sessionStorage");
        return false;
    } else {
        //主逻辑业务
        var storage = window.sessionStorage;
        value = JSON.stringify(value);
        storage.setItem(c_name, value);
    }
    // var expiredays = 1;  // 保存1天
    // var exdate = new Date()
    // exdate.setDate(exdate.getDate() + expiredays)
    // document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}

// 取回cookie
function getCookie(c_name) {
    if (!window.sessionStorage) {
        alert("浏览器不支持sessionStorage");
        return '';
    } else {
        //主逻辑业务
        var storage = window.sessionStorage;
        var result = storage.getItem(c_name);
        return JSON.parse(result);
    }
    // if (document.cookie.length > 0) {
    //     c_start = document.cookie.indexOf(c_name + "=")
    //     if (c_start != -1) {
    //         c_start = c_start + c_name.length + 1
    //         c_end = document.cookie.indexOf(";", c_start)
    //         if (c_end == -1) c_end = document.cookie.length
    //         return unescape(document.cookie.substring(c_start, c_end))
    //     }
    // }
    // return ""
}

// 清除某一个sessionStorage
function clearCookie(c_name, type) {
    if (!window.sessionStorage) {
        _msg("浏览器不支持sessionStorage");
        return '';
    } else {
        //主逻辑业务
        var storage = window.sessionStorage;
        if (!type) {
            storage.removeItem(c_name);
        } else {
            storage.clear();
        }
    }
}

// 退出
function _uot() {
    setOnline(0);
    clearCookie('user');
    clearCookie('userid');
    clearCookie('date');
    clearCookie('sex');
}

// 登录
function _login() {
    _uot();
    _url({ title: '登录', url: 'user/login_win' });
}

// 返回首页
function _hone() {
    window.location.href = root_url + 'index.html';
}

// 跳转
function _url(data, url, login) {
    // window.event.cancalBubble = true;
    if (login && !userid) {
        _login();
        return;
    }

    if (data && typeof data == 'object') {
        var str = '?';
        for (var p in data) {
            var s = '&' + p + '=' + data[p];
            str = str + s;
        }
        str = str.split('?&')[1];
        var _s = escape(str)
        url = url ? url : 'win';
        url = str ? url + '.html?' + _s : url + '.html';
        // if (data && data.new_win == 1) {
        //     window.open(base_url + url);
        //     _log(base_url + url)
        // } else {
        window.location.href = base_url + url;
        // }
    } else {
        window.location.href = data;
    }

}



// 加载框
function _loading() {
    var html = '<div id="loading"></div>';
    $('body').append(html);
}

// 隐藏加载框
function _loadingClose() {
    $('#loading').remove();
}



// 提示框
function _msg(msg) {
    // var html = '<div id="msg"><span class="msg-text">' + msg + '</span></div>';
    var html = '<div id="msg"><div class="msg-wrap flex-col flex-c"> <i class="msg-icon"></i> <span class="msg-text">' + msg + '</span> </div></div>';
    $('body').append(html);
    setTimeout(function () {
        $('#msg').remove();
    }, 1000);
}
var _alertFn;

function _alert(msg, callback) {
    _alertFn = function () {
        $('#alert').remove();
        if (typeof callback == 'function') {
            callback();
        }
    };
    var html = `<div id="alert">
    <div class="alert-content flex-col flex-c">
        <i class="js-close-icon" onclick="$('#alert').remove();"></i>
        <i class="msg-icon"></i>
        <div class="alert-txt">${msg}</div>
        <button class="alert-btn" onclick="_alertFn()">确定</button>
    </div>
</div>`;
    $('body').append(html);
}

var _confirmFn;

function _confirm(data, callback) {
    if (!data) return;
    var msg = data.msg;
    var title = data.title || '提示';
    var buttons = data.btn ? data.btn : ['确定', '取消'];
    var subText = buttons[0];
    var cancelText = buttons[1];
    // var subText = data.sub || '确定';
    // var cancelText = data.cancel || '取消';

    var html = `<div id="confirm">
    <div class="confirm-content">
            <i class="js-close-icon" onclick="$('#confirm').remove()"></i>
        <div class="confirm-title">${title}</div>
        <div class="confirm-txt">${msg}</div>
        <div class="confirm-btn">
            <button class="confirm-del-btn" onclick="_confirmFn(0)">${cancelText}</button>
            <button class="confirm-sub-btn" onclick="_confirmFn(1)">${subText}</button>
        </div>
    </div>
</div>`;
    $('body').append(html);
    _confirmFn = function (index) {
        $('#confirm').remove();
        if (typeof callback == 'function') {
            callback(index);
        }
    };
}
var _submitFn;

function _submit(data, callback) {
    if (!data) return;
    var title = data.title || '温馨提示：';
    var msg = data.msg;
    var subText = data.sub || '确定';
    var cancelText = data.cancel || '取消';
    var html = `
    <div class="submit-wrap" id="submit-wrap">
        <div class="submit-content">
            <div class="close-wrap">
                <div class="title">${title}</div>
                <div class="close" onclick="$('#submit-wrap').remove()"></div>
            </div>
            <div class="content">
                ${msg}
            </div>
            <div class="submit-footer flex-bt">
                <button class="btn cancel" onclick="_submitFn(1)">${cancelText}</button>
                <button class="btn submit" onclick="_submitFn(2)">${subText}</button>
            </div>
        </div>
    </div>
    `;
    $('body').append(html);
    _submitFn = function (index) {
        $('#submit-wrap').remove();
        if (typeof callback == 'function') {
            callback(index);
        }
    };
}

var _actionFn;

function _action(title, buttons, callback) {
    var btn = '';
    for (var i = 0, len = buttons.length; i < len; i++) {
        btn = btn + '<li class="a-list" onclick="_actionFn(' + (i + 1) + ')">' + buttons[i] + '</li>'
    }
    var html = `
    <div class="" id="action">
        <div class="action">
            <ul class="a-ul"> ${btn} </ul>
            <button class="cancel" onclick="$('#action').remove()">取消</button>
        </div>
    </div>
    `;
    $('body').append(html);
    _actionFn = function (index) {
        $('#action').remove();
        if (typeof callback == 'function') {
            callback(index);
        }
    };
}

function _closeToWin() {
    window.history.back(-1);
}

function timerWin() {
    setTimeout(function () {
        window.history.back(-1);
    }, 1000)
}


// 返回
function _close() {
    var pageParam = getParam();
    // if (pageParam['new_win'] == 1) {
    //     window.close();
    // } else {
    window.history.back(-1);
    // }
}

// 清除所有HTML
function clearHtml(s) {
    if (!s) {
        return s;
    }
    var dd = s.replace(/<\/?.+?>/g, "");
    var dds = dd.replace(/  /g, "");
    return dds;
}

// 随机数 包括最小值 不包括最大值
function getRandom(min, max) {
    var num = Math.floor(Math.random() * (max - min + 1) + min);
    return num;
}
// 验证手机号码
function checkMobile(mobile) {
    if (mobile == "") {
        return false;
    } else {
        var valid_rule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/; // 手机号码校验规则
        if (!valid_rule.test(mobile)) {
            return false;
        }
        return true;
    }
}


// 查看用户详情
function go_userInfo(id, name, sex) {
    var mysex = getCookie('sex');

    if (sex && mysex == sex) {
        _msg('不可查看同性的详细信息')
        return;
    }
    _url({
        url: 'frame0/user_info_frame',
        title: name,
        user_id: id,
        moreType: 1
    }, 'user_win')
}

// 返回对象
function returnObj(str) {
    if (!str) return;
    var arr = str.split(',');
    var obj = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        var s = arr[i].replace(/\s+/g, "");
        s = s.split(':');
        obj[s[0]] = s[1];
    }
    return obj;
}


// 打开app
function openApp() {
    var obj = {
        msg: '该功能需仅限app操作，是否下载app?',
        btn: ['前去下载', '取消'],
    }
    _confirm(obj, function (bIndex) {
        if (bIndex == 1) {
            window.location.href = appurl;
        }
    })
}
// 加载
function _load(el, name) {
    var url = base_url + name + '.html';
    $(el).load(url);
}

// 判断是否登录
function judgeLogin() {
    // var admin = getCookie('admin');
    // if (!admin) {
    //     _login();
    // }
    getCookie
}

function _log(data) {
    // console.log(data);
    // console.clear();
}

// 设置上下线 1上线 0下线
function setOnline(state) {
    if (!myuserid) return;
    _ajax('set_online_state.php', function (ret) {}, {
        state: state,
        user_id: myuserid,
    })
}


// 获取用户资料 user_id 被查看人 to_user 是否需要传我的id
function _getUser(callback, user_id, to_user) {
    var myid = getCookie('userid');
    var uid = user_id ? user_id : myid;
    var obj = to_user ? {
        user_id: uid,
        to_user: myid
    } : {
        user_id: uid
    };
    obj.longitude = getCookie('lon');
    obj.latitude = getCookie('lat');

    _ajax('user_info.php', function (ret) {
        _log(JSON.stringify(ret))
        if (ret && ret.code == 200) {
            if (!ret.result.id) {
                _alert('获取用户信息失败，请重新登录', function () {
                    _login();
                })
                return;
            }
            if (ret.result.is_banned == 1) {
                _alert('该账号已被冻结，解封时间为' + ret.result.banned_end_time + ', 如有疑问，请联系客服', function () {
                    _login();
                })
                return;
            }
            callback(ret)
        } else {
            _alert('获取用户信息失败，请重新登录', function () {
                _login();
            })
        }
    }, obj)
}



// 上传单图
function _upImg(img, callback) {
    if (!img || (typeof img == 'string' && img.indexOf('disk/') != -1)) {
        callback(img);
        return;
    }
    var formData = new FormData();
    formData.append("image", img);
    formData.append("thumb", 1);
    $.ajax({
        url: phpurl + 'index.php/api/Tool/imagesUpload', //请求接口
        type: "POST", //请求方式
        dataType: 'json',
        data: formData, //请求参数（这里将参数都保存在formData对象中）
        processData: false, //因为data值是FormData对象，不需要对数据做处理。
        contentType: false, //默认为true,不设置Content-type请求头
        success: function (result) {
            _log(JSON.stringify(result))
            if (typeof result == 'string') {
                result = JSON.parse(result);
            }
            if (result && result.code == 200) {
                if (typeof callback == 'function') {
                    callback(result.data.image);
                }
            } else {
                callback(img);
            }
        },
        error: function (err, status) {
            // _log(JSON.stringify(err))
        }
    })
}

// 上传多图
function _upImgs(img, callback) {
    var myid = getCookie('admin');
    if (!img || img.length==0) {
        callback(img);
        return;
    }
    var formData = new FormData();
    for(var i=0,len=img.length;i<len;i++){
        formData.append("image[" + i + "]", img[i]);
        // formData.append("image[]", img);
    }
    formData.append("thumb", 1);
    var headers;
    if (window.sessionStorage.getItem('kefu_token')) {
        headers = {
            'Authorization': window.sessionStorage.getItem('kefu_token')
        }
    }
    $.ajax({
        headers: headers,
        url: phpurl + 'index.php/api/Tool/imagesUploads', //请求接口
        type: "POST", //请求方式
        dataType: 'json',
        data: formData, //请求参数（这里将参数都保存在formData对象中）
        processData: false, //因为data值是FormData对象，不需要对数据做处理。
        contentType: false, //默认为true,不设置Content-type请求头
        success: function (result) {
            _log(JSON.stringify(result))
            if (typeof result == 'string') {
                result = JSON.parse(result);
            }
            if (result && result.code == 200) {
                if (typeof callback == 'function') {
                    callback(result.data.images);
                }
            } else {
                callback(img);
            }
        },
        error: function (err, status) {
            // _log(JSON.stringify(err))
        }
    })
}

// 通知后端将 点赞 报名等信息推送给 发布者uid
function pushMsg(uid) {
	_log(uid)
	if (!uid) return;
	var obj = {
		user_id: uid
	};
	_ajax('Home/Privatechat/getreadcount', function (ret, err) {
	}, { data: JSON.stringify(obj) })
}


// 更新消息数量
function changeMsgNum(chat_count, message_count) {
	var num = chat_count + message_count;
	if (num && num > 0) {
		num = num > 99 ? '99+' : num;
		$('footer .num').text(num);
		$('footer .num').removeClass('new-hide');
		if (chat_count > 0) {
			chat_count = chat_count > 99 ? '99+' : chat_count;
			$('#js-cnum').text(chat_count);
			$('#js-cnum').removeClass('new-hide');
		} else {
			$('#js-cnum').addClass('new-hide');
		}
		if (message_count > 0) {
			message_count = message_count > 99 ? '99+' : message_count;
			$('#js-mnum').text(message_count);
			$('#js-mnum').removeClass('new-hide');
		} else {
			$('#js-mnum').addClass('new-hide');
		}
	} else {
		$('#js-cnum').addClass('new-hide');
		$('#js-mnum').addClass('new-hide');
		$('footer .num').addClass('new-hide');
	}
}
